<template>
  <div class="p-5">
    <div class="card-box box mt-5">
      <a-button type="primary" @click="addNewItem">新增主项</a-button>

      <a-form>
        <a-table :columns="columns" :data-source="newdata.list" class="components-table-demo-nested" rowKey="key"
          :pagination="false" :defaultExpandAllRows="true">
          <template #bodyCell="{ column, record, index }">

            <template v-if="column.key === 'tag'">
              <a-input v-model:value="record.tag" placeholder="请输入食谱类型(例如：早餐)" />
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="addComponent(record, index)">新增食物</a-button>
              <a-button type="link" danger @click="deleteItem(index)">
                删除
              </a-button>
            </template>
          </template>

          <template #expandedRowRender="{ record, index: parentIndex }">
            <a-table :columns="columns2" :data-source="record.items" class="components-table-demo-nested custom-table"
              :pagination="false" rowKey="key">
              <template #bodyCell="{ column, record: subRecord, index: subIndex }">
                <template v-if="column.key === 'cover'">
                  <a-image :width="100" :src="subRecord.cover" />
                </template>
                <template v-if="column.key === 'weightGram'">
                  <a-form-item name="重量">
                    <a-input-number v-model:value="subRecord.weightGram" addon-after="g"
                      placeholder="请输入"></a-input-number>
                  </a-form-item>
                </template>

                <template v-if="column.key === 'action'">
                  <a-button type="link" danger @click="deleteComponent(record.items, subIndex)">
                    删除
                  </a-button>
                </template>
              </template>
            </a-table>
          </template>
        </a-table>
      </a-form>
    </div>
    <selectFood v-model:value="open" @submit="selectfoodbtn" />
  </div>
</template>

<script setup>
import { reactive, watch, ref, nextTick } from 'vue';
import { getcomlist } from "#/hooks/common.ts";
import * as api from '#/api/core/nutrition.ts'

import selectFood from '#/components/selectFood/selectFood.vue'

// 定义 props 和 emit
const props = defineProps({
  value: {
    type: Array,
    default: () => [] // 提供默认值，避免 undefined
  },
  type: {
    type: String,
    default: 'add'
  }
})

const open = ref(false)
const emits = defineEmits(['update:value'])





// 表格列配置
const columns = [
  {
    title: '食谱类型',
    dataIndex: 'tag',
    key: 'tag',
    align: "center",
  },
  {
    title: '操作',
    key: 'action',
    align: "center",
  },
];

const columns2 = [
  {
    title: '封面',
    dataIndex: 'cover',
    key: 'cover',
    align: "center",
  },
  {
    title: '食物名称',
    dataIndex: 'name',
    key: 'name',
    align: "center",
  },
  {
    title: '数值',
    dataIndex: 'weightGram',
    key: 'weightGram',
    align: "center",
  },
  {
    title: '操作',
    key: 'action',
    align: "center",
  },
];

// 响应式数据存储
const newdata = reactive({
  list: [],
  nutrlist: [],
  currentindex: 0
});

// 获取分类列表
const { comclasslist } = getcomlist(9);



const flaga = ref(false)
watch(() => props.value,

  async (newV) => {
    if (props.type == 'update') {


      if (!flaga.value) {

        console.log('回显食物数据', newV);
        newdata.list = newV.map((e) => {
          return {
            tag: e.tag,
            kwy: e.id,
            items: e.items.map((i) => {
              return {
                ...i.food,
                weightGram: i.weightGram
              }
            })
            // ...e
          }
        })

        await nextTick()
        flaga.value = true
      }
    }
  }, {
  deep: true
})

watch(() => newdata.list,
  (newV) => {

    if (flaga.value) {
      let temp = newdata.list.map((e) => {
        return {
          ...e,
          items: e.items.map(((i) => {

            return {
              foodId: i.id,
              weightGram: i.weightGram
            }
          }))
        }
      })
      emits('update:value', temp)
    }
  }, {
  deep: true
}

)




// 新增主项
const addNewItem = () => {
  const newId = newdata.list.length + 1;
  newdata.list.push({
    tag: "",
    key: `${newId}-1`,
    items: []
  });
};

// 删除主项
const deleteItem = (index) => {
  newdata.list.splice(index, 1);
  // 重新生成 id 避免重复（可选，根据需求）
  newdata.list.forEach((item, i) => item.id = i + 1);
};

// 新增食物
const addComponent = (record, index) => {

  open.value = true
  newdata.currentindex = index
};

// 确定选择的食物
const selectfoodbtn = (e) => {


  newdata.list[newdata.currentindex] = {
    ...newdata.list[newdata.currentindex],

    items: e
  }
  console.log('选中的实物', e, newdata.list

  );

}




</script>
<style scoped>
.custom-table {
  --header-bg-color: #f0f2f5;
  /* 表头背景色（浅灰，可自定义） */
  --header-text-color: #1890ff;
  /* 表头文字色（蓝色，可自定义） */
}

/* 覆盖 Ant Design 表格表头样式 */
.custom-table /deep/ .ant-table-thead>tr>th {
  background-color: var(--header-bg-color) !important;
  /* 表头背景 */
  color: var(--header-text-color) !important;
  /* 表头文字颜色 */
  font-weight: 600;
  /* 文字加粗（可选） */
}

/* 展开行的子表格表头样式（如果需要与主表格一致） */
.custom-table /deep/ .ant-table-thead>tr>th.ant-table-column-has-actions {
  background-color: var(--header-bg-color) !important;
}
</style>
